import Popup from "@/components/Popup/Popup";
import { defineComponent, reactive, ref } from "vue";
import styles from "./Add.module.less";
import to from "await-to-js";
import _ from "lodash";
import { CloudUploadOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { $upload } from "@/apis/common/upload/upload";
import { message } from "ant-design-vue";
export default defineComponent({
  props: {
    service: {
      type: Object,
    }
  },
  emits: ["change"],
  setup(props, { expose, emit }) {
    const addPopupRef = ref(null as any);
    const state = reactive({
      type: '',
      form: {
        id: undefined, //歌曲id
        cid: null, //分类id
        englishName: null, //英文名称
        chineseName: null, //中文名称
        coverPic: null, //封面
        disabled: null, //是否可用
        languageType: null, //语言类型
        sort: null, //排序
        isRecommend: null, //推荐状态
        level: null, //难度
        isDemo: null, //是否演示
        enCollectUrl: null, //英文版个人收藏图片
        zhDisplay: null,  // 中文是否显示
        enDisplay: null,  //英文是否显示
      },
      options: {
        cid: [
          {
            id: 0,
            name: '作为一级菜单',
            children: [],
          }
        ],
        level: [
          {
            label: '入门',
            value: 1,
          },
          {
            label: '初级',
            value: 3,
          },
          {
            label: '提高',
            value: 5,
          },
          {
            label: '高级',
            value: 7,
          },
          {
            label: '挑战',
            value: 9,
          },
        ],
      }
    } as any)

    //获取分类下拉列表
    const getTreeList = async () => {
      const [err, res]: any = await to(props.service?.tree());
      if (!err) {
        state.options.cid[0].children = res.data?.data || [];
      }
    }
    //获取详情
    const getDetail = async () => {
      const [err, res]: any = await to(props.service?.detail(state.form.id));
      if (!err) {
        const obj = res.data?.data || {};
        Object.keys(state.form).forEach(x => {
          if (x === 'enCollectUrl') {
            state.form.enCollectUrl = obj.ecollectUrl
          } else {
            state.form[x] = obj[x]
          }
        })
      }
    }
    //打开弹窗
    const open = async ({ type, id }) => {
      state.type = type;
      state.form.id = id;
      await getTreeList();
      if (type === 'edit') {
        await getDetail();
      }
      addPopupRef.value.open();
    }

    const englishName_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入英文名称!');
      }
    };

    const chineseName_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入中文名称!');
      }
    };

    const sort_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入排序!');
      }
    };

    //验证
    const rules = {
      cid: [{ required: true, trigger: 'change' }],
      englishName: [{ required: true, validator: englishName_check, trigger: 'change' }],
      chineseName: [{ required: true, validator: chineseName_check, trigger: 'change' }],
      coverPic: [{ required: true, trigger: 'change' }],
      sort: [{ required: true, validator: sort_check, trigger: 'change' }]
    }
    //上传
    const imageUpload = async (file, key) => {
      const formData = new FormData();
      formData.set('file', file);
      const [err, res]: any = await to($upload(formData))
      if (!err) {
        state.form[key] = res.data?.url || '';
      }
      return false;
    }
    //确认按钮loading
    const submitLoading = ref(false)

    //确认提交
    const submit = async () => {
      submitLoading.value = true;
      const params = _.cloneDeep(state.form)
      if (!params.cid) {
        message.error('请选择分类');
        return;
      }
      if (!params.englishName) {
        message.error('请输入英文名称');
        return;
      }
      if (!params.chineseName) {
        message.error('请输入中文名称');
        return;
      }
      if (!params.coverPic) {
        message.error('请上传封面');
        return;
      }
      if (!params.enCollectUrl) {
        message.error('请上传英文版个人收藏图片');
        return;
      }
      if (!params.disabled) {
        message.error('请选择可用状态');
        return;
      }
      if (!params.languageType) {
        message.error('请选择语言类型');
        return;
      }
      if (!params.sort) {
        message.error('请输入排序');
        return;
      }
      if (!params.isRecommend) {
        message.error('请选择推荐状态');
        return;
      }
      if (!params.level) {
        message.error('请选择难度');
        return;
      }
      if (!params.isDemo) {
        message.error('请选择是否演示');
        return;
      }
      if (!params.zhDisplay) {
        message.error('请选择是否中文显示');
        return;
      }
      if (!params.enDisplay) {
        message.error('请选择是否英文显示');
        return;
      }
      const [err, res]: any = await to((state.type === 'edit' ? props.service?.edit : props.service?.add)(params))
      if (!err) {
        message.success(state.type === 'edit' ? '编辑成功' : '添加成功');
        addPopupRef.value.close();
        emit('change');
      }
      submitLoading.value = false;
    }
    expose({
      open,
    })
    return () => (
      <Popup
        ref={addPopupRef}
        title={state.type === 'edit' ? "编辑歌曲" : '添加歌曲'}
        width="800px"
        oriState={state}
        v-slots={{
          footer: () => <>
            <a-button type="primary" loading={submitLoading.value} onClick={() => { submit() }}>确定</a-button>
            <a-button onClick={() => { addPopupRef.value.close() }}>取消</a-button>
          </>
        }}
      >
        <div class={styles.container}>
          <div class={styles.formBox}>
            <a-form model={state.form} rules={rules} label-col={{ style: { width: '150px', marginRight: '10px' } }} wrapper-col={{ span: 28 }}>
              <a-form-item required label="分类" name="cid">
                <a-tree-select
                  v-model:value={state.form.cid}
                  tree-data={state.options.cid}
                  placeholder="请选择分类"
                  fieldNames={{
                    label: 'name', value: 'id', children: 'children'
                  }}
                ></a-tree-select>
              </a-form-item>
              <a-form-item required label="英文名称" name="englishName">
                <a-input v-model:value={state.form.englishName} placeholder="请输入英文名称" />
              </a-form-item>
              <a-form-item required label="中文名称" name="chineseName">
                <a-input v-model:value={state.form.chineseName} placeholder="请输入中文名称" />
              </a-form-item>
              <a-form-item required label="封面" name="coverPic">
                <div class={styles.imageBox}>
                  {
                    state.form.coverPic ?
                      <img src={state.form.coverPic} /> :
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon} />
                      </div>
                  }
                  <a-upload
                    before-upload={(file) => imageUpload(file, "coverPic")}
                    showUploadList={false}
                    name="file"
                  >
                    <div class={styles.uploadDemo}>
                      <CloudUploadOutlined class={styles.icon} />
                      <span>请上传封面</span>
                    </div>
                  </a-upload>
                </div>
              </a-form-item>
              <a-form-item required label="英文版个人收藏图片" name="enCollectUrl">
                <div class={styles.imageBox}>
                  {
                    state.form.enCollectUrl ?
                      <img src={state.form.enCollectUrl} /> :
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon} />
                      </div>
                  }
                  <a-upload
                    before-upload={(file) => imageUpload(file, "enCollectUrl")}
                    showUploadList={false}
                    name="file"
                  >
                    <div class={styles.uploadDemo}>
                      <CloudUploadOutlined class={styles.icon} />
                      <span>请上传封面</span>
                    </div>
                  </a-upload>
                </div>
              </a-form-item>
              <a-form-item required label="是否可用" name="disabled">
                <a-radio-group
                  v-model:value={state.form.disabled}
                  name="radioGroup"
                >
                  <a-radio value={0}>正常</a-radio>
                  <a-radio value={1}>停用</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item required label="语言类型" name="languageType">
                <a-radio-group
                  v-model:value={state.form.languageType}
                  name="radioGroup"
                >
                  <a-radio value={0}>中文</a-radio>
                  <a-radio value={1}>英文</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item required label="排序" name="sort">
                <a-input-number min={0} v-model:value={state.form.sort} placeholder="请输入排序" style="width: 50%" />
              </a-form-item>
              <a-form-item required label="推荐状态" name="isRecommend">
                <a-radio-group
                  v-model:value={state.form.isRecommend}
                  name="radioGroup"
                >
                  <a-radio value={0}>不推荐</a-radio>
                  <a-radio value={1}>推荐</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item required label="难度" name="level">
                <a-select
                  v-model:value={state.form.level}
                  options={state.options.level}
                  style="width: 50%"
                  placeholder="请选择难度"
                ></a-select>
              </a-form-item>
              <a-form-item required label="是否演示" name="isDemo">
                <a-radio-group
                  v-model:value={state.form.isDemo}
                  name="radioGroup"
                >
                  <a-radio value={0}>不演示</a-radio>
                  <a-radio value={1}>演示</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item required label="是否中文显示" name="zhDisplay">
                <a-radio-group
                  v-model:value={state.form.zhDisplay}
                  name="radioGroup"
                >
                  <a-radio value={0}>隐藏</a-radio>
                  <a-radio value={1}>显示</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item required label="英文是否显示" name="enDisplay">
                <a-radio-group
                  v-model:value={state.form.enDisplay}
                  name="radioGroup"
                >
                  <a-radio value={0}>隐藏</a-radio>
                  <a-radio value={1}>显示</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </Popup>
    )
  }
})